<script setup lang="ts">
	import changeBoxd from './change-box.vue'
	import SectionTitle from '@/wxcomponents/section-title'
	import productItem from '@/wxcomponents/product-item-new'
	import ListItem from '@/wxcomponents/list-item'
	import MainWrapper from '@/wxcomponents/main-wrapper'
	import PrizeDialogContent from '@/wxcomponents/prize-dialog-content'
	import { onLoad, onReachBottom, onShow, onPullDownRefresh } from "@dcloudio/uni-app";
	import {
		loadYiFanShangDetail,
		listYiFanShangRecords,
		listYiFanShangRemain,
		listYiFanShangCountRanking,
		listYiFanShangWorthRanking,
	} from "@/api/yifanshang";
	import GamePanel from './shared/game-panel'
	import PrizeTab from './shared/prize-tab'
	import RecordContent from './shared/record-content'
	import RankingTabs from './shared/ranking-tabs'
	import RankingContent from './shared/ranking-content'
	import GameRecharge from './shared/game-recharge'

	import { ref, computed } from 'vue'
	let explainshow = ref(false)
	const gameId = ref(0)
	const detail = ref({})
	const rechargePrices = ref([])
	const showBanners = ref([])
	const dialogItem = ref({})
	const currentIndex = ref(1)
	const isCouponModalVisible = ref(false)
	const remainList = ref([])
	const recordList = ref([])

	// 服务器端统计的总数据量
	const recordListTotal = ref(null)

	// 记录数据分页
	const recordListPage = ref(1)

	const ouHuangRankingList = ref([])
	const countRankingList = ref([])
	const specialTypes = ref({
		'First': true,
		'Last': true,
		'W': true,
		'最终': true
	})
	let safetop = ref(0)
	// onShareAppMessage((res) =>  {
	//     if (res.from === 'button') {
	//       // 来自按钮的分享
	//       // 返回分享的内容
	//       return {
	//         title: detail.value.name,
	//         imageUrl: detail.value.main_photo// 分享卡片的图片，可选
	//       }
	//     }
	// })
	// function sharegame() {
	// 	 wx.showShareMenu({
	// 		withShareTicket: true,
	// 		menus: ['shareAppMessage', 'shareTimeline']
	// 	  });

	// }
	const shareData = computed(() => { // 分享的数据
		return {
			title: detail.value.name,
			imageUrl: detail.value.main_photo
		}
	})
	function getsafetop() {
		uni.getSystemInfo({
			success: function (res) {
				// res.safeAreaInsets 包含了 safeAreaInsets.top 和 safeAreaInsets.bottom
				safetop.value = res.safeAreaInsets.top;
			}
		});
	}
	onPullDownRefresh(async () => {
		await loadYiFanShang(currentIndex.value)
		uni.stopPullDownRefresh()
	})
	onLoad(async (options) => {
		const id = options.id || 0
		const index = options.index || 1
		getsafetop()
		if (!id) {
			uni.showToast({
				title: 'id参数错误',
				icon: 'none'
			})
			return
		}
		gameId.value = id
		currentIndex.value = Number(index)

		await loadYiFanShang(currentIndex.value)
		uni.$mpShare = shareData.value // 修改uni.$mpShare的值

	});
	onShow(() => {
		uni.$mpShare = shareData.value // 修改uni.$mpShare的值
	})
	function openexplainshow() {
		explainshow.value = true;
	}
	function closeexplainshow() {
		explainshow.value = false;
	}
	function changeBox() {
		explainshow.value = true;
	}
	onReachBottom(async () => {
		if (activeTab.value !== '记录') {
			return
		}
		await listGiftRecords({ refresh: false })
	})

	async function refresh() {
		await loadYiFanShang(currentIndex.value)
	}

	/**
	 * 从【一番赏】复制
	 * 接口的名字不重要，其实就是加载游戏数据
	 */
	async function loadYiFanShang(index) {
		const params = {
			game_id: gameId.value,
			type: '欧皇赏',
			index
		}
		const res = await loadYiFanShangDetail(params)
		const data = res.data || {}

		const products = data.products || []
		const special_products = data.special_products || []

		let allProducts = []
		// 商品价格从单位分转为元
		for (let i = 0; i < special_products.length; i++) {
			special_products[i].price = (special_products[i].price / 100).toFixed(2)
			special_products[i].showStock = "数量:" + special_products[i].stock + "/" + special_products[i].count

			allProducts.push(special_products[i])
		}

		for (let i = 0; i < products.length; i++) {
			products[i].price = (products[i].price / 100).toFixed(2)
			products[i].showStock = "数量:" + products[i].stock + "/" + products[i].count
			allProducts.push(products[i])
		}
		data['products'] = allProducts

		showBanners.value = []
		for (let i = 0; i < data.banners.length; i++) {
			showBanners.value.push({
				'main_photo': data.banners[i]
			})
		}

		const buyCounts = [1, 3, 5]
		rechargePrices.value = []
		const newPrices = []
		for (let i = 0; i < buyCounts.length; i++) {
			const buyPrice = data['price'] * buyCounts[i]

			newPrices.push({
				'price': data['price'],
				'show_price': (buyPrice / 100).toFixed(2),
				'class': 'recharge-' + buyCounts[i],
				'count': buyCounts[i]
			})
		}
		rechargePrices.value = newPrices

		detail.value = data
	}

	async function prevBox() {
		// console.log('------prevBox', activeTab.value, rankingTab.value)
		let index = currentIndex.value - 1
		if (index <= 0) {
			index = index + detail.value['box_count']
		}
		currentIndex.value = index

		await changeTab(activeTab.value)
		// await loadYiFanShang(index)
	}

	async function nextBox() {
		// console.log('------nextBox', activeTab.value, rankingTab.value)
		const index = currentIndex.value % (detail.value['box_count']) + 1
		currentIndex.value = index

		await changeTab(activeTab.value)
		// await loadYiFanShang(index)
	}

	function goBack() {
		uni.switchTab({
			url: '/pages/index/index'
		})
	}

	function showDialogImage(item) {
		dialogItem.value = {
			image: item.image,
			name: item.name,
			price: item.price
		}
		console.log(dialogItem.value)
		isCouponModalVisible.value = true
	}

	function closeCouponModal() {
		isCouponModalVisible.value = false;
	}
	// , '排行'
	const tabs = ref(['赏品', '余量', '记录', '购买说明'])
	const activeTab = ref('赏品')

	const rankingTab = ref('次数排行')

	async function changeRankingTab(t : string) {
		rankingTab.value = t
		console.log('-----changeRankingTab', t)
		if (t === '次数排行') {
			await listCountRanking()
		} else if (t === '欧皇排行') {
			await listOuHuangRanking()
		}
	}

	async function listGiftRemain() {
		const params = {
			game_id: gameId.value,
			index: currentIndex.value,
			type: detail.value['type']
		}
		const res = await listYiFanShangRemain(params)
		const data = res.data || {}
		const items = data.items || []

		remainList.value = items
	}

	async function listGiftRecords({ refresh = true } = {}) {
		if (!refresh && recordListTotal.value === recordList.value.length) {
			// 已获取了全部数据量，不再发送加载更多的请求
			return
		}

		const params = {
			page: refresh ? 1 : recordListPage.value + 1,
			game_id: gameId.value,
			index: currentIndex.value,
			type: detail.value['type'],
			size: 15,
		}
		const res = await listYiFanShangRecords(params)
		const data = res.data || {}
		const items = data.items || []

		recordListTotal.value = data.total
		recordList.value = refresh ? items : recordList.value.concat(items)
		recordListPage.value = params.page
	}

	async function listCountRanking() {
		const params = {
			game_id: gameId.value,
			index: currentIndex.value,
			type: detail.value['type']
		}
		const res = await listYiFanShangCountRanking(params)
		const data = res.data || {}
		const items = data.items || []
		countRankingList.value = items
	}

	// 列出欧皇排行
	async function listOuHuangRanking() {
		const params = {
			game_id: gameId.value,
			index: currentIndex.value,
			type: detail.value['type']
		}
		const res = await listYiFanShangWorthRanking(params)
		const data = res.data || {}
		const items = data.items || []
		ouHuangRankingList.value = items
	}

	async function changeTab(t : string) {
		activeTab.value = t
		if (t === '赏品') {
			await loadYiFanShang(currentIndex.value)
		} else if (t === '余量') {
			await listGiftRemain()
		} else if (t === '记录') {
			await listGiftRecords({ refresh: true })
		} else if (t === '排行') {
			if (rankingTab.value === '次数排行') {
				await listCountRanking()
			} else if (rankingTab.value === '欧皇排行') {
				await listOuHuangRanking()
			} else {
				await listCountRanking()
			}
		}
	}
</script>

<template>
	<view class="main-wrapper">
		<view class="page-head" :style="{top:safetop+'px'}">
			<!-- <image class="arrow" src="/static/icons/nav-arrow.png" @click="goBack()" /> -->
			<uni-icons type="arrow-left" color="white" size="30" @click="goBack"></uni-icons>
			<section-title title="欧皇赏" class="gap-top" />
		</view>
		<van-dialog use-slot :show="isCouponModalVisible" :show-confirm-button="false" width="312">
			<prize-dialog-content :image="dialogItem.image" :name="dialogItem.name" :price="dialogItem.price"
				v-on:close="closeCouponModal" />
		</van-dialog>

		<game-panel :index="currentIndex" :isshow="false" :data="detail" />
		<view class="product-control">
			<view @click="prevBox">
				<image src="/static/owo/icon-btn/last.png" class="nicon"></image>
			</view>
			<view @click="changeBox">
				<image src="/static/owo/icon-btn/change.png" class="cicon"></image>
			</view>
			<view @click="nextBox">
				<image src="/static/owo/icon-btn/next.png" class="nicon"></image>
			</view>
		</view>
		<view class="prize-tabs">
			<prize-tab v-for="tab in tabs" :key="tab" :active="activeTab === tab" @click="() => changeTab(tab)">
				{{ tab }}
			</prize-tab>
		</view>

		<view class="tab-content">
			<view v-if="activeTab === '赏品'" class="products-list">
				<product-item v-for="(item, index) in detail.products" :key="index" :title="item.name" :pic="item.image"
					:price="item.price" :type="item.type" :percent="item.percent" class="product-item"
					:soldout="item.stock === 0" :bottom-text="item.showStock" @click="showDialogImage(item)" />

			</view>

			<view v-if="activeTab === '余量'" class="leftover-list">
				<list-item v-for="(item, index) in remainList" :key="index">
					<view class="leftover-item">
						<view class="prize-info">
							<!-- <text class="text-type">{{ item.type }}</text> -->
							<text class="text-name">{{ item.name }}</text>
							<text class="text-amount">{{ item.remain }} / {{ item.count }}</text>
						</view>
						<view class="prize-extra">
							<image v-if="item.type in specialTypes" class="gift-icon" src="/static/owo/gift-text.png"
								mode="widthFix"></image>
							<image v-if="!(item.type in specialTypes)" class="gift-icon" src="/static/owo/rate-text.png"
								mode="widthFix"></image>
							<text v-if="!(item.type in specialTypes)">{{ item.percentage_zh }}</text>
						</view>
					</view>
				</list-item>
			</view>

			<view v-if="activeTab === '记录'" class="record-list">
				<list-item v-for="(item, index) in recordList" :key="index">
					<record-content :avatar-src="item.avatar" :name="item.name" :datetime="item.created_at"
						:prize-type="item.type" :prize-name="item.game_type" style="width: 100%" />
				</list-item>
			</view>
			<view v-if="activeTab === '购买说明'" class="desc-list">
				<view style="height: 360rpx;">
					<scroll-view scroll-y="true" style="height: 360rpx;">
						<text class="pcontent">
							{{detail.instruction}}
						</text>
					</scroll-view>
				</view>
			</view>
			<view v-if="activeTab === '排行'" class="ranking">
				<ranking-tabs :value="rankingTab" :tabs="['次数排行', '欧皇排行']" @change="changeRankingTab" />
				<view class="tab-content ranking-list" v-if="rankingTab === '次数排行'">
					<list-item v-for="(item, index) in countRankingList" :key="index">
						<ranking-content :avatar-src="item.avatar" :name="item.nickname" :buy="item.count"
							:ranking="index+1" style="width: 100%" />
					</list-item>
				</view>

				<view class="tab-content ranking-list" v-if="rankingTab === '欧皇排行'">
					<list-item v-for="(item, index) in ouHuangRankingList" :key="index">
						<ranking-content :avatar-src="item.avatar" :name="item.nickname" :buy="item.count"
							:ranking="index+1" style="width: 100%" />
					</list-item>
				</view>
			</view>
		</view>

		<game-recharge class="bottom-panel" :title="detail.title" :prices="rechargePrices" :gameIndex="currentIndex"
			:gameId="detail.id" :gameType="detail.type" :image="detail.main_photo" :price="detail.price" :ifFull="0"
			@success="refresh" />
		<van-popup :show="explainshow" custom-style="background-color: rgba(0, 0, 0, 0)">
			<view class="guizebg">
				<view class="guizeitem">
					<image class="guizeitemimage" src="/static/owo/text-board-bg.png"></image>
					<view class="plabel" style="width: 100%;">
						<scroll-view style="height: 720rpx;" scroll-y="true">
							<change-boxd :id="detail.id" :type="detail.type" :count="detail.box_count"></change-boxd>
						</scroll-view>
					</view>
				</view>
				<image src="/static/owo/close.png" class="close" @click="closeexplainshow"></image>
			</view>
		</van-popup>
	</view>
</template>


<style lang="scss">
	.box-group-list {
		min-width: 100%;
		width: auto;
		overflow-x: auto;
		color: white;
		font-size: 15px;
		display: flex;
		align-items: center;
		gap: 26px;
		height: 40px;

		.box-group {
			min-width: fit-content;
			font-weight: 600;
		}
	}

	.prize-list {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		height: auto;

		.prize-item {
			width: 100%;
		}
	}

	@import 'src/static/scss/maincommon';

	view {
		box-sizing: border-box;
	}

	.product-control {
		box-sizing: border-box;
		width: 100%;
		padding: 20rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.nicon {
			width: 200rpx;
			height: 80rpx;
		}

		.cicon {
			width: 264rpx;
			height: 92rpx;
		}
	}

	.main-wrapper {
		/* width: 100%; */
		width: 750rpx;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		padding-bottom: 20px;
		box-sizing: border-box;
		// padding-top: 80px;
		position: relative;
	}

	.arrow {
		width: 40rpx;
		height: 40rpx;
		vertical-align: middle;
	}

	.guizebg {
		width: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.guizeitem {
		position: relative;
	}

	.guizeitemimage {
		width: 580rpx;
		height: 790rpx;
	}

	.plabel {
		position: absolute;
		left: 0rpx;
		top: 46rpx;
		padding:30rpx;
		height: 360px;
		overflow: hidden;
	}

	.ptitle {
		height: 80rpx;
		line-height: 80rpx;
		font-size: 36rpx;
		color: #ffffff;
	}

	.pcontent {
		color: #ffffff;
		line-height: 32rpx;
		font-size: 28rpx;
		margin-bottom: 6rpx;
	}

	.close {
		width: 56rpx;
		height: 56rpx;
		margin-top: 20rpx;
	}

	.page-head {
		position: fixed;
		display: flex;
		top: 0;
		gap: 10px;
		width: 150px;
		// line-height: 88px;
		align-items: center;
		z-index: 100;
	}

	.prize-intro {
		color: white;
		font-weight: medium;
		font-size: 10px;
		margin: 12px 0;
		display: inline-block;
	}

	.prize-tabs {
		display: flex;
		gap: 10px;
		padding: 15rpx;
	}

	.tab-content {
		margin-top: 1em;
	}

	.products-list {
		width: 100%;
		padding: 15rpx;
		display: flex;
		box-sizing: border-box;
		flex-wrap: wrap;
		justify-content: flex-start;
	}

	.leftover-list {
		display: flex;
		flex-direction: column;
		gap: 0;
	}

	.leftover-item {
		font-size: 12px;
		font-weight: medium;
		display: flex;
		justify-content: space-between;
		width: 100%;

		.prize-info {
			display: flex;
			width: 80%;
			justify-content: flex-start;
			color: #FFFFFF;
			font-size: 24rpx;

			.text-type {
				width: 20%;
			}

			.text-amount {
				width: 20%;
			}

			.text-name {
				width: 40%;
			}
		}

		.prize-extra {
			flex: 1;
			display: flex;
			justify-content: flex-end;
			align-items: center;
			gap: 1em;
		}

		.gift-icon {
			width: 23px;
		}
	}

	.desc-list {
		box-sizing: border-box;
		margin: 24rpx;
		height: 400rpx;
		padding: 24rpx;
		background-image: url("/static/owo/dongli-winnerbg1.png");
		background-position: 0 0;
		background-repeat: no-repeat;
		background-size: 100%;

	}

	.record-list {
		display: flex;
		flex-direction: column;
		gap: 0;
	}

	.ranking {
		width: 100%;
	}

	.ranking-list {
		display: flex;
		flex-direction: column;
		gap: 0;
	}

	.with-bottom-panel {
		position: relative;
		padding-bottom: 200px;
	}

	.bottom-panel {
		position: fixed;
		bottom: 280rpx;
		right: 0rpx;
		z-index: 33;
		width: 152rpx;
		height: 160px;
	}

	.product-item {
		width: 24%;
		margin-right: 1%;
		display: flex;
		justify-content: space-around;
	}

	.product-item:nth-child(4n+4) {
		margin-right: 0;
	}
</style>